package com.eqdd.yiqidian.ui.yiqichuang.fragment;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.eqdd.yiqidian.CoolRefreshRecyclerViewFragmentCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.ChuangwenListBean;
import com.eqdd.yiqidian.bean.rebuild.ZhangPageResultBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.yiqichuang.ChuangArticleInfoActivity;
import com.eqdd.yiqidian.ui.yiqiyue.ArticleInfoActivity;
import com.eqdd.yiqidian.ui.yiqiyue.YueLabelListActivity;
import com.eqdd.yiqidian.utils.DateUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;

/**
 * @author吕志豪 .
 * @date 18-1-25  下午3:27.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class ChuangwenFragment extends BaseFragment {
    CoolRefreshRecyclerViewFragmentCustom dataBinding;
    private SlimAdapterEx<ChuangwenListBean> slimAdapterEx;
    private int pageNum = 0;
    private String url;
    private Bundle bundle;
    private MVCCoolHelper<List<ChuangwenListBean>> mvcHelper;
    private String guid;
    private int isHomePage;
    private int categoryId;
    private String para;
    private String categoryName="";

    @Override
    protected void setView() {
    }

    @Override
    protected void initData() {
        if (slimAdapterEx == null) {
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_80, new SlimInjector<ChuangwenListBean>() {
                @Override
                public void onInject(ChuangwenListBean data, IViewInjector injector) {
                    injector.image(R.id.iv_head, data.getAvatar())
                            .text(R.id.stv_name, data.getNickname())
                            .text(R.id.tv_title, data.getTitle())
                            .gone(R.id.rl_bg)
                            .invisible(R.id.iv_option)
                            .text(R.id.tv_depart, DateUtil.parseRongTime(data.getPostTime()))
                            .image(R.id.iv_img, data.getPicUrl())
                            .text(R.id.tv_content, data.getSplendidContent())
                            .visibility(R.id.iv_img, TextUtils.isEmpty(data.getPicUrl().trim()) ? View.GONE : View.VISIBLE)
                            .text(R.id.tv_source, data.getSource() == 0 ? "创客空间" : "其它")
                            .text(R.id.stv_msg, data.getCommentCount() + "评论")
                            .text(R.id.stv_look, data.getPageviews() + "阅读")
                            .text(R.id.stv_support, data.getPraiseCount() + "点赞")
                            .with(R.id.recyclerViewLabel, view -> {
                                if (data.getMatchedTrade() == null) {
                                    return;
                                }
                                RecyclerView recyclerViewLabel = (RecyclerView) view;
                                List<String> stringList = new ArrayList<>();
                                for (String s : data.getMatchedTrade().split(";")) {
                                    if (!TextUtils.isEmpty(s)) {
                                        stringList.add(s);
                                    }
                                }
                                recyclerViewLabel.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
                                SlimAdapterEx<String> slimAdapterExLabel = SlimAdapterEx.create().register(R.layout.list_item_74, new SlimInjector<String>() {
                                    @Override
                                    public void onInject(String data, IViewInjector injector) {
                                        injector.gone(R.id.iv_clear)
                                                .text(R.id.tv_content, data);
                                    }
                                }).attachTo(recyclerViewLabel).updateData(stringList);
                                ItemClickSupport.addTo(recyclerViewLabel)
                                        .setOnItemClickListener((recyclerView, position, v) -> {
                                            Bundle bundle = new Bundle();
                                            bundle.putString(Config.LABEL, slimAdapterExLabel.getDataItem(position));
                                            startActivity(YueLabelListActivity.class, bundle);
                                        });
                            });
                }
            }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
            ModelRx2DataSource<ChuangwenListBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
                @Override
                public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                    pageNum = page == 1 ? 0 : pageNum;
                    return OkGo.<ZhangPageResultBean<List<ChuangwenListBean>>>post(HttpConfig.BASE_URL + url)
                            .params("page", pageNum)
                            .params("userGuid", TextUtils.isEmpty(guid) ? AppConstent.user.getGuid() : guid)
                            .params("owner", TextUtils.isEmpty(guid) ? AppConstent.user.getGuid() : guid)
                            .params("ishomepage", isHomePage)
                            .params("categoryId", categoryId)
                            .params("keyWords", para)
                            .params("categoryName", categoryName)
                            .converter(new JsonConverter<ZhangPageResultBean<List<ChuangwenListBean>>>() {
                                @Override
                                public void test() {
                                    super.test();
                                }
                            }).adapt(new FlowableBody<>())
                            .flatMap(listResultBean -> {
                                pageNum = listResultBean.getNextpage();
                                if (listResultBean.getStatus() == 200) {
                                    return Flowable.just(listResultBean.getItems() == null ? new ArrayList<ChuangwenListBean>() : listResultBean.getItems());
                                } else {
                                    ToastUtil.showShort(listResultBean.getMsg());
                                    return Flowable.just(new ArrayList<>());
                                }
                            });

                }
            });
            mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
            mvcHelper.setDataSource(dataSource);
            mvcHelper.setAdapter(slimAdapterEx);
            mvcHelper.refresh();
            ItemClickSupport.addTo(dataBinding.recyclerView)
                    .setOnItemClickListener((recyclerView, position, v) -> {
                        bundle = new Bundle();
                        bundle.putInt(Config.ID, slimAdapterEx.getDataItem(position).getId());
                        ((BaseActivity) getActivity()).startActivityForResult(ChuangArticleInfoActivity.class, bundle, position);
                    });
        }
    }

    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        url = getArguments().getString(Config.URL);
        guid = getArguments().getString(Config.GUID);
        isHomePage = getArguments().getInt(Config.IS_HOMEPAGE, 1);
        categoryId = getArguments().getInt(Config.ID, 0);
        return dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_cool_recycler_view, null, false);

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.DELETE) {
            slimAdapterEx.getData().remove(requestCode);
            slimAdapterEx.notifyItemRemoved(requestCode);
        } else if (resultCode == Config.REFRESH || resultCode == Config.SUCCESS) {
            mvcHelper.refresh();
        }
    }

    public void search(CharSequence para) {
        this.para = para.toString();
        mvcHelper.refresh();
    }

    public void search(CharSequence para, CharSequence categoryName) {
        this.categoryName = categoryName.toString();
        this.para = para.toString();
        mvcHelper.refresh();
    }
}
